package com.baizhi.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.service.CmfzAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>
 * InnoDB free: 11264 kB 前端控制器
 * </p>
 *
 * @author xiaoxiao
 * @since 2020-08-18
 */
@RestController
@RequestMapping("/cmfz-admin")
public class CmfzAdminController {
    @Autowired
    private CmfzAdminService cmfzAdminService;
    @PostMapping("/login")
    public ModelAndView login(CmfzAdmin cmfzAdmin, String code, HttpSession session) {
        ModelAndView mav = new ModelAndView("redirect:/login.jsp");
        String realCode = (String) session.getAttribute("realCode");
        String errorMsg;
        if (!realCode.equals(code)) {
            errorMsg = "验证码错误";
            mav.addObject("errorMsg", errorMsg);
        }
        CmfzAdmin login = cmfzAdminService.login(cmfzAdmin);
        if (login != null) {
            //登录成功
            session.setAttribute("cmfzAdmin", login);
            mav.setViewName("redirect:/main.jsp");
        } else {
            //登录失败
            errorMsg = "用户名或密码错误";
            mav.addObject("errorMsg", errorMsg);
        }
        return mav;
    }
    @GetMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse resp, HttpServletRequest req) throws IOException {
        //用糊涂工具类获取一个验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        //取到验证码的值
        String realCode = captcha.getCode();
        //将值存在session作用域中，以便比对
        HttpSession session = req.getSession();
        session.setAttribute("realCode",realCode);
        System.out.println(captcha);
        //通过流响应给浏览器
        captcha.write(resp.getOutputStream());
    }
}
